<?php

namespace app\admin\model\wanlshop;

use think\Model;


class Packageytrule extends Model
{


    // 表名
    protected $name = 'wanlshop_package_yt_rule';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'type_text'
    ];

    protected static function init()
    {
        self::afterInsert(function ($row) {
            $data = $row->getData();
            if($data['type'] == 'alone'){
                $row->rule_ids = $data['id'];
                $row->save();
            }else{
                $content = json_decode($data['content'],true);
                $rule_ids = [];
                foreach ($content as $val){
                    $ids = explode(',',$val['rule_ids']);
                    $rule_ids = array_merge($rule_ids,$ids);
                }
                $row->rule_ids = implode(',',$rule_ids);
                $row->save();
            }
        });
        self::beforeUpdate(function ($row) {
            $data = $row->getData();
            if($data['type'] == 'alone'){
                $row->rule_ids = $data['id'];
            }else{
                $content = json_decode($data['content'],true);
                $rule_ids = [];
                foreach ($content as $val){
                    $ids = explode(',',$val['rule_ids']);
                    $rule_ids = array_merge($rule_ids,$ids);
                }
                $row->rule_ids = implode(',',$rule_ids);
            }
        });
    }
    
    public function getTypeList()
    {
        return ['alone' => __('Type alone'), 'mix' => __('Type mix')];
    }


    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type']) ? $data['type'] : '');
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }




}
